`
IP_ADDRESS="${1}"
case ${IP_ADDRESS} in
192.168.*)
echo "Network is 192.168.x.x"
;;
10.0.*)
echo "Network is 10.0.x.x"
;;
*)
echo "Could not identify the network."
;;
esac
Listing 2-18
A case statement to check an IP address and determine its network
We define a variable that expects one command line argument to be passed
(${1}) and saves it to the IP_ADDRESS variable. We then use a pattern to check
whether the IP_ADDRESS variable starts with 192.168. and a second pattern
to checks whether it starts with 10.0..
We also define a default wildcard pattern using *, which returns a default
message to the user if nothing else has matched.
Save this file as case_ip_address_check.sh and run it:
$ chmod u+x case_ip_address_check.sh
$./case_ip_address_check.sh 192.168.12.55
Network is 192.168.x.x
$./case_ip_address_check.sh 212.199.2.2
Could not identify the network.
This script is available at https://github.com/dolevf/Black-Hat-
Bash/blob/master/ch02/case_ip_address_check.sh.
Text Processing and Parsing
One of the most common things you’ll find yourself doing in bash is
processing text. You can parse text on the command line by running one-off
commands, or use a script to store parsed data in a variable that you can act on in
some way. In both cases, the skill is important to many scenarios.
To test the commands in this section on your own, download the sample log
file from https://github.com/dolevf/Black-Hat-Bash/blob/master/ch02/log.txt. This
file is space-separated, and each segment represents a specific data type, such as
the client’s source IP address, timestamp, HTTP method, HTTP path, HTTP User
Agent field, HTTP status code, and more.
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks